﻿package com.rragona.utils.genericUtils 
{
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.EventDispatcher;
	
	import flash.net.URLRequest;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	
	/**********************************************************************************************************************
	 * @version				1.0
	 * @author				rragona
	 * 
	 * @history
	 * [1.0.0]
	 *	- Class Created
	 * 
	 * @description
	 * This class simplifies the loading of external files. 
	 *********************************************************************************************************************/
	
	public class ContentLoader extends EventDispatcher
	{
		private var _request:URLRequest;
		
		public var loader:Loader;
		
		public function ContentLoader(path:String)
		{
			_request = new URLRequest(path);
			loader = new Loader();
			
			loader.load(_request);
			
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadComplete);
		}
		
		public function getLoadInfo():LoaderInfo
		{
			return loader.contentLoaderInfo;
		}
		
		private function onIOError(e:IOErrorEvent):void
		{
			loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
			loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onLoadComplete);
			
			dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR, true));
		}
		
		private function onLoadComplete(e:Event):void
		{
			loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
			loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onLoadComplete);
			
			dispatchEvent(new Event(Event.COMPLETE, true));
			
			loader = null;
		}
		
	}
	
}